package com.example.lenovo.downloaddemo.activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.lenovo.downloaddemo.R;
import com.example.lenovo.downloaddemo.bean.Customer;
import com.example.lenovo.downloaddemo.bean.ProductInfoBean;
import com.example.lenovo.downloaddemo.http.AppConfig;
import com.example.lenovo.downloaddemo.http.datasource.MDataSource;
import com.example.lenovo.downloaddemo.http.okhttp.utils.AppContext;
import com.example.lenovo.downloaddemo.http.okhttp.utils.Collintion;
import com.example.lenovo.downloaddemo.http.okhttp.utils.CommonUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.MD5;
import com.example.lenovo.downloaddemo.http.okhttp.utils.ToastUtil;
import com.example.lenovo.downloaddemo.sqlite.LoadListCallBack;
import com.example.lenovo.downloaddemo.util.StatusBarUtil;
import com.example.lenovo.downloaddemo.util.TextStyleLanguage;
import com.example.lenovo.downloaddemo.util.TimeUtil;
import com.example.lenovo.downloaddemo.view.TitleBarView;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Request;

public class ProductInfoActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.productinfo_Titbar)
    TitleBarView titleBarView;
    @Bind(R.id.iv_Product_logo)
    ImageView iv_Product_logo;//产品logo
    @Bind(R.id.product_info_name)
    TextView product_info_name;//产品名称
    @Bind(R.id.product_download_Num)
    TextView product_download_Num;//下载数量
    @Bind(R.id.product_verson)
    TextView product_verson;//版本号
    @Bind(R.id.download)
    ImageView downLoad;//下载

    private List<ImageView> image_List;


    @Bind(R.id.brief_introduction)
    TextView brief_introduction;//产品简介

    @Bind(R.id.down_tv)
    TextView down_tv;

    @Bind(R.id.product_info_banner)
    Banner product_info_banner;//轮播图
    private ProductInfoBean bean;
    private List<String> list;//轮播地址集合
    Callback.Cancelable cancelable;
    private ProgressDialog progressDialog;

    private String allString;
     String filePath=AppContext.getInstance().getExternalFilesDir(null)+"/download/test.apk";
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String returnMesssage= (String) msg.obj;
                Gson gson=new Gson();
                bean=gson.fromJson(returnMesssage,ProductInfoBean.class);
                if(bean.getCode()==200){
                    if(!TextStyleLanguage.isEngLish()) {
                        product_info_name.setText(bean.getData().getGood_name());
                        brief_introduction.setText(AppContext.getInstance().getResources().getText(R.string.productjianjie)+"："+bean.getData().getDesc());
                    }else{
                        product_info_name.setText(bean.getData().getGood_name_en());
                        brief_introduction.setText(AppContext.getInstance().getResources().getText(R.string.productjianjie)+"："+bean.getData().getDesc_en());
//                        downLoad.setText("DownLoad");
                    }
                    product_download_Num.setText(AppContext.getInstance().getResources().getText(R.string.download_num)+":"+bean.getData().getDownload_num()+"");
                    product_verson.setText(AppContext.getInstance().getResources().getText(R.string.version)+"："+bean.getData().getApp_version());

                    Picasso.with(AppContext.getInstance())
                            .load(AppConfig.IP+bean.getData().getGood_pic())
                            .into(iv_Product_logo);



                    list=new ArrayList<>();
//                    list.add("http://192.168.1.222:2010"+bean.getData().getApp_screenshot());
//                    Log.e( "handleMessage: ", "http://192.168.1.222:2010"+bean.getData().getApp_screenshot());
//                    Log.e( "handleMessage: ====", bean.getData().getApp_screenshot());
                    String img_url=bean.getData().getApp_screenshot();
                    String[] str=img_url.split(",");

                    for (int i = 0; i < str.length; i++) {
                        Log.e("图片地址===",AppConfig.IP+str[i]);
                        list.add(AppConfig.IP+str[i]);
                        product_info_banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                imageView.setScaleType(ImageView.ScaleType.CENTER);
                                Glide.with(context).load((String)path).into(imageView);
                            }
                        });

                    }
                    product_info_banner.setImages(list);
                    product_info_banner.start();

                }
            }


        }
    };

//    public class ImageLoaderBanner extends ImageLoader {
//        @Override
//        public void displayImage(Context context, Object path, ImageView imageView) {
////Glide设置图片的简单用法
//            Glide.with(context).load(path).into(imageView);
//        }
//    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_info);
        ButterKnife.bind(this);
        x.view().inject(this);
        initView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("onPause","onPause");
        progressDialog.dismiss();
//        if(!cancelable.isCancelled()) {
//            cancelable.cancel();
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("onStop","onStop");
//        if(!cancelable.isCancelled()) {
//            cancelable.cancel();
//        }
    }

    @Override
    protected void initView() {
//        if(!TextStyleLanguage.isEngLish()){
           down_tv.setText(AppContext.getInstance().getResources().getText(R.string.download));
//        }else{
//            holder.name_More.setText(data.get(i).getGood_name_en());
//        }
        image_List=new ArrayList<ImageView>() ;

        StatusBarUtil.setMargin(AppContext.getInstance(),titleBarView);
        titleBarView.setTitle(AppContext.getInstance().getResources().getString(R.string.productinfo));
        titleBarView.showBackButton(true);
        product_info_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        product_info_banner.setIndicatorGravity(BannerConfig.CENTER);
        product_info_banner.setDelayTime(3000);//设置轮播间隔时间
        int width = CommonUtils.getScreenWidth(AppContext.getInstance());
        int height=CommonUtils.getScreenHeight(AppContext.getInstance())/2;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
//
        product_info_banner.setLayoutParams(lp);

        downLoad.setOnClickListener(this);


    }


    @Override
    protected void onResume() {
        super.onResume();
        if(CommonUtils.isNetOk(AppContext.getInstance())) {
            initData();
        }else{
            ToastUtil.makeText(AppContext.getInstance(),"Fail!");
        }
        setProgressDialog();
    }

    private void initData() {
        Intent intent=getIntent();
        int goodsid=intent.getIntExtra("goodsid",0);
        Log.e( "goodsid===" ,goodsid+"");


        /**
         * 建立请求表单，添加上传服务器的参数
         */
        HashMap<String, String> map = new HashMap<>();
        map.put("model", "index");
        map.put("method", "goodsInfo");
        map.put("good_id",goodsid+"");

        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        allString=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(allString));
        Log.e("拼接字符串",allString);
        Log.e("签名===",sign);
        map.put("sign",sign);

        MDataSource<Customer> dataSource = new MDataSource<>(AppContext.getInstance());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("产品详情", "loadString 产品详情 : " + string);

                Message message=Message.obtain();
                message.what=1;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });



    }
    private void deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
            } else {
                Toast.makeText(getApplicationContext(), "删除单个文件" + filePath$Name + "失败！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "删除单个文件失败：" + filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
        }
    }





    private void downLoadAPK(String url,String name){
//        执行网络请求操作

//        downLoad.setText("下载中...");
        RequestParams params = new RequestParams(url);
        params.setAutoRename(false);  //设置是否根据头信息命名文件
        params.setAutoResume(true);  //设置文件下载断点续传
        params.setExecutor(new PriorityExecutor(2,true));  //设置加载图片的线程池
        params.setCancelFast(true);  //设置是否可以立即停止
//        设置缓存的路径


//        if(new File(filePath).exists()){
//            //已存在  询问是否删除
//            AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
//            builder.setTitle(getResources().getString(R.string.tishi)).setMessage(getResources().getString(R.string.quedinganzhuang))
//                    .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
////                              执行apk安装的步骤
//                            deleteSingleFile(filePath);
//
////                                deleteSingleFile(file.toString());
////                                Log.e("删除安装包==","删除成功");
//
//                        }
//                    }).setNegativeButton(getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
//            });
//            builder.create().show();
//
//        }else{
//
//        }
        params.setSaveFilePath(filePath);
        cancelable = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(final File file) {
//                请求成功时，回调的方法
                AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
                builder.setTitle(AppContext.getInstance().getResources().getString(R.string.tishi)).setMessage(AppContext.getInstance().getResources().getString(R.string.quedinganzhuang))
                        .setPositiveButton(AppContext.getInstance().getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                              执行apk安装的步骤
                                downLoad.setImageResource(R.mipmap.download_apk_);
                                downLoad.setClickable(true);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                if(Build.VERSION.SDK_INT >= 24){//大于7.0
                                    Uri apkUri=FileProvider.getUriForFile(AppContext.getInstance(),"com.example.lenovo.downloaddemo.fileprovider",file);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                }else {
                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                }
                                ProductInfoActivity.this.startActivity(intent);

//                                deleteSingleFile(file.toString());
//                                Log.e("删除安装包==","删除成功");

                            }
                        }).setNegativeButton(AppContext.getInstance().getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        deleteSingleFile(file.toString());
                    }
                });
                builder.create().show();
            }
            @Override
            public void onError(Throwable throwable, boolean b) {
                Log.e("onError",throwable.getMessage().toString());
//              请求失败时，会执行的方法
            }
            @Override
            public void onCancelled(CancelledException e) {
                Log.e("onCancelled",e.getMessage().toString());
//              请求被取消时，会执行的方法
                progressDialog.dismiss();
//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onFinished() {
//              请求完成时，会执行的方法
                Log.e("onFinished","onFinished");
                progressDialog.dismiss();
            }
            @Override
            public void onWaiting() {
                Log.e("onWaiting","onWaiting");
//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onStarted() {
                Log.e("onStarted","onStarted");
//                开始网络请求时，会执行的方法
                progressDialog.show();
            }
            @Override
            public void onLoading(long total, long current, boolean b) {
                Log.e("onLoading","onLoading");
//                  设置对话框当中的进度条
                progressDialog.setProgress((int)(current*100/total));
            }
        });
    }

    private void setProgressDialog() {
//        ImageView imageView =new ImageView(AppContext.getInstance());
//        Picasso.with(AppContext.getInstance()).load(url)
//                .into(imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setIcon(R.mipmap.download);
        progressDialog.setTitle(AppContext.getInstance().getResources().getString(R.string.xiazaiAPK));
//        progressDialog.setView();
        progressDialog.setMessage(AppContext.getInstance().getResources().getString(R.string.nulixiazai));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, AppContext.getInstance().getResources().getText(R.string.pause), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                暂停下载
                cancelable.cancel();
                downLoad.setClickable(true);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy","onDestroy");
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.download:
//                if(!new File(filePath).exists()) {
                    if(CommonUtils.isNetOk(AppContext.getInstance())) {
                            downLoadAPK(bean.getData().getApp_apk(), bean.getData().getPackageX());


//                        downLoad.setClickable(false);
                    }else{
                        ToastUtil.makeText(AppContext.getInstance(),"Fail!");
                    }
//                }else {
//                    AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
//                    builder.setTitle(getResources().getString(R.string.tishi)).setMessage(getResources().getString(R.string.shifoushanchu))
//                            .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    downLoadAPK(bean.getData().getApp_apk(), bean.getData().getPackageX());
//                                }
//                            }).setNegativeButton(getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                            ToastUtil.makeText(AppContext.getInstance(),"Fail!");
//                        }
//                    });
//                     builder.create().show();
//                }
                break;
        }
    }
}
